package cn.cdm.controller;

import cn.cdm.domain.MiaoshaUser;
import cn.cdm.redis.MiaoshaUserKey;
import cn.cdm.redis.RedisService;
import cn.cdm.redis.SaltKey;
import cn.cdm.result.Result;
import cn.cdm.service.MiaoshaUserService;
import cn.cdm.util.MD5Util;
import cn.cdm.util.MyStringUtil;
import cn.cdm.util.UserCreate;
import cn.cdm.vo.LoginVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

@Controller
// 支持输入 http://localhost:8080/login 的url地址,来访问登录页面；也支持输入 http://localhost:8080/login/to_login 的url地址,来访问登录页面
@RequestMapping("/login")
public class LoginController {

    private static final Logger log = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    UserCreate userCreate;

    @Autowired
    MiaoshaUserService userService;

    @Autowired
    RedisService redisService;

    /**
     * 打上RequestMapping注解的请求方式
     * （1）如果方法上的@RequestMapping注解没有设置method属性，则get和post请求默认都可以访问。如：
     *                   @RequestMapping("/to_login")
     *
     * （2）如果方法上的@RequestMapping注解设置了method属性，则只能是相应的请求方式可以访问。如：
     *                  @RequestMapping(value = "/to_login", method = RequestMethod.GET)
     * @return
     * @throws Exception
     */
//   @RequestMapping("/to_login")
//    @RequestMapping(value = "/to_login", method = RequestMethod.GET)
    @RequestMapping(value = {"/to_login", "/", ""}, method = RequestMethod.GET)
    public String toLogin() throws Exception{
        return "login";
    }

//    @RequestMapping("/do_login", method = RequestMethod.POST) Web层的方法，会进入UserArgumentResolver的入参检验方法
//    @RequestMapping(value = "/do_login", produces={"application/json;charset=UTF-8"})
    // produces属性，设置返回响应数据的消息类型以及编码，消息类型为application/json；编码为UTF-8
    @RequestMapping(value = "/do_login", produces= MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody // 该接口的响应数据，后端以json格式返回给前端
    public Result<String> doLogin(HttpServletResponse response, @Valid LoginVo loginVo) {
        log.info("登录信息：" + loginVo.toString());
        // 登录
        String loginSessionId = userService.login(response, loginVo);
        log.info("返回，用户的sessionId：{}", loginSessionId);
        return Result.success(loginSessionId);
    }


    @RequestMapping("/test")
    @ResponseBody
    public MiaoshaUser test(HttpServletRequest request) {
        log.debug("进入test");
        Cookie[] cookies = request.getCookies();
        String token = null;
        for (Cookie cookie : cookies) {
            if("token".equals(cookie.getName())){
                token = cookie.getValue();
                break;
            }
        }
        MiaoshaUser user =  redisService.get(MiaoshaUserKey.token, token, MiaoshaUser.class);
        System.out.println(user);
        return user;
    }

    @RequestMapping("/login_safe")
    public String toLoginSafe() {
        return "login_safe";
    }

    @RequestMapping("/getSalt")
    @ResponseBody
    public Result getSalt(String mobile){
        System.out.println(mobile);
        String suiji_salt = MyStringUtil.getString(10);
        redisService.set(SaltKey.salt, mobile, suiji_salt);

        redisService.set(MiaoshaUserKey.id, ""+ mobile, MD5Util.inputPassToFormPass(""));
        return Result.success(suiji_salt);
    }

    @RequestMapping("/do_login_safe")
    @ResponseBody
    public Result<Boolean> doLoginSafe(HttpServletResponse response, @Valid LoginVo loginVo) {
        log.debug("新登录：" + loginVo.toString());
        //登录
        userService.login(response, loginVo);
        log.debug("返回");
        return Result.success(true);
    }

}
